﻿var myModalMessage;
var progress = new Progress();
var myZtree;
var timeOut = 20;
var asubmit, next, areturn, currentColor, divUserTitle, myModal, divUser, btnSubmitWorkflow, submitFlag = false, $form, history_content,
    suggest, formdata, btnClose, attachment_parm, asubmits, attachment_content, ul_tab, monitor_content, divProgress, monitorModal, signatureModal;
var nextActivity;
currentColor = getCurrentColor();
function GenerateBtn(obj) {
    var btn = btnHtml.clone();
    $(".shortcut-title", btn).html(obj.title);

    for (l in obj.parm)
        btn.attr(l, obj.parm[l]);
    var bar = $(btn.find('div')[0]);
    if (obj.class) {
        bar.attr('class', '');
        bar.addClass(obj.class);
    }
    btn.attr('href', '#');
    return btn;
}


var Setting = {
    view: {
        dblClickExpand: false,
        showLine: true
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: null
        },
        key: {
            name: "userName"
        }
    },
    check: {
        enable: true,
        chkDisabledInherit: true
    }
}

var monitor = {}

var core = {
    modal: undefined,
    submittime: 0,
    runState: {
        /// <summary>
        /// 运行中
        /// </summary>
        running: 0,
        /// <summary>
        /// 挂起
        /// </summary>
        suspended: 1,
        /// <summary>
        /// 终止
        /// </summary>
        terminated: 2,
        /// <summary>
        /// 完成
        /// </summary>
        finished: 3
    },


    Init: function (parm) {

        myModal = $("#userModal"),
            divUser = $("#divUser", myModal),
            divUserTitle = $("#divUserTitle", myModal),
            btnSubmitWorkflow = $("#btnSubmitWorkflow", myModal);
        var me = this;
        history_content = historyConainer;
        me.IsDetail = parm.IsDetail;
        me.templateId = parm.templateId;

        me.IsCreate = true;

        me.Instance = {};
        me.Template = SqlHelper.GetTemplateById(parm.templateId);
        $.request("/workflow/form/find/templateId", {id: parm.templateId}, function (data) {
            me.Form = data;
        }, false, false);


        var formdata = {};
        if (parm.id) {


            me.workItem = parm;
            me.instanceId = parm.instanceId;
            me.IsCreate = !me.instanceId;
            me.currentactivity = me.workItem.activityId ?
                me.Template.activities.where(me.workItem.activityId, 'id') :
                me.Template.activities.where(ActivityType.End, 'activityType');


            $.request("/workflow/instance/find", {id: me.instanceId}, function (data) {
                me.Instance = data;
            }, false, false);

            function getdata(formObjList) {
                if (formObjList.length == 0)
                    return null;
                var obj = {};
                $.each(formObjList, function (i, val) {
                    obj[val.fieldDbName] = val.data;
                })
                return obj;
            }


            $.request("/workflow/form/data/find", {instanceId: me.instanceId}, function (data) {

                $.each(me.currentactivity.activityForms, function (p, val) {
                    var myForm = val.form;
                    formdata[myForm.formName] = getdata(data.findall(myForm.formName, "formName"));
                    if (myForm.subform && myForm.subform.length > 0) {
                        var list = [];
                        $.each(myForm.subform, function (q, subform) {
                            var datalist = data.findall(subform.formName, "formName");
                            var falg = true, rowIndex = 0;
                            while (falg) {
                                var subobj = datalist.findall(rowIndex++, "sort");
                                if (subobj.length > 0) {
                                    list.push(getdata(subobj));
                                } else falg = false;
                            }
                            formdata[myForm.formName][subform.formName] = list;
                        });
                    }
                })

            }, false, false);
            me.loadHistroy();
        }
        else {
            me.currentactivity = me.Template.activities.where(ActivityType.Drafting, 'activityType')
        }
        var btn;
        me.loadAttachment(), btn = me.loadBtn(formdata);

        wfParm.LoadData(me, me.currentactivity, formdata);

        var total = 0, flag = 0, result;

        if (btn) {
            me.showsuggestion();
            $.each(me.currentactivity.activityForms, function (i, val) {
                if (val.permissions == 6) {
                    ++total;
                    var myForm = val.form;
                    validateList[myForm.formName].submitBtn = btn;
                    validateList[myForm.formName].submitHandler = function (obj, container, $btn) {
                        if (flag == 0)
                            result = {};
                        result[myForm.formName] = obj;
                        if (myForm.subform && myForm.subform.length > 0) {
                            $.each(myForm.subform, function (j, subform) {
                                var list = gridparms[subform.formName].data;
                                result[myForm.formName][subform.formName] = list;
                            });
                        }
                        ++flag;
                        //验证通过
                        if (flag == total) {
                            flag = 0;
                            if (me.needSelectUser(nextActivity)) {
                                me.bindselectuserBtn(result);
                            }
                            else {
                                me.excute(result);
                            }
                        }
                    }
                    $("#" + myForm.formName).validate(validateList[myForm.formName]);
                }
            });

            //没有需要提交的表单
            if (total == 0) {
                btn.click(function () {
                    //需要选人，绑定选人按钮
                    if (me.needSelectUser(nextActivity)) {
                        me.bindselectuserBtn();
                    }
                    //不需要选人，直接提交
                    else {
                        me.excute(result);
                    }
                });
            }
        }

        $("#monitorCotnainer").monitor(this);

    },

    progressInit: function () {
        progress.init();
        progress.setProgress(10);
        progress.start();
        this.animate();
    },

    excute: function (result, nodes, callback) {
        if (callback)
            callback();
        var me = this;

        this.progressInit();
        if (me.currentactivity.activityType == ActivityType.Drafting) {
            var workItem = me.createWorkflow();

            progress.setProgress(20);
            wfParm.SaveData(result);
            progress.setProgress(40);
            me.saveData(result, workItem, function () {
                progress.setProgress(60);
                me.submit(nodes, workItem);
            }, me.error);
        } else {
            if (!result) {
                progress.setProgress(60);
                me.submit(nodes, me.workItem);
            } else {
                progress.setProgress(40);
                me.saveData(result, me.workItem, function () {
                    progress.setProgress(60);
                    me.submit(nodes, me.workItem);
                }, me.error)

            }

        }
    },

    bindselectuserBtn: function (result) {
        var that = this;
        $("#btnSubmitWorkflow").unbind("click").on("click", function () {
            var nodes = myZtree.getCheckedNodes();
            if (nodes.length == 0) {
                alert("请选择处理人！");
                return;
            }
            if (confirm("确认提交？")) {
                that.excute(result, nodes, function () {
                    myModal.modal("hide");
                });
            }
        });
    },

    needSelectUser: function (activity) {
        var me = this;
        //需要选人
        if (!(activity.activityType == ActivityType.End || activity.IS_AUTOMATIC == 1)) {
            divUserTitle.html($.format('{0}->{1}', core.currentactivity.activityName, activity.activityName));
            myModal.modal();

            function BindUser(userList, val) {
                var submitData = new Array();
                divUser.html('');
                var divContainer = $("<div class='col-lg-12'>");
                var divContent = $("<div style=' height:230px; overflow:auto;'>");
                divContainer.append($("<div>").append(divContent));
                $("#divUser").append(divContainer);

                var nodes = userList;
                var ul = $("<ul>").attr("class", "ztree").css("width", "auto");
                myZtree = $.fn.zTree.init(ul, Setting, nodes);
                myZtree.expandAll(true);
                divContent.append(ul);
            }

            //绑定事件
            BindUser(activity.participantses);
            return true;
        }
        return false;
    },

    //显示审批意见输入框
    showsuggestion: function () {

        if (this.IsCreate)
            return;
        var suggestPanel = $("#suggestPanel");
        suggestPanel.css("display", "block");
        suggest = $("#suggest", suggestPanel);
    },

    //获取审批意见
    getsuggestion: function () {
        if (suggest && suggest.length > 0)
            return suggest.val();
        return "";
    },

    //提交失败
    error: function () {
        $.request("", {'instanceId': instanceId}, function () {
            alert("提交失败");
        });
    },

    //保存数据列转行
    saveData: function (result, workItem, handler, handlerError) {

        function objToList(obj, formName, rowIndex) {
            var data = []
            for (i in obj) {
                if (obj[i] instanceof Array) {
                    var myName = i;
                    $.each(obj[i], function (j, val) {
                        data = data.concat(objToList(val, myName, j));
                    });
                } else
                    data.push({
                        instanceId: workItem.instanceId,
                        fieldDbName: i,
                        'formName': formName,
                        data: obj[i],
                        'sort': rowIndex == undefined ? '' : rowIndex
                    });
            }
            return data;
        }

        var list = [];
        for (i in result) {
            list = list.concat(objToList(result[i], i));
        }
        $.request("/workflow/form/data/save", list, function () {
            if (handler)
                handler();
        }, function () {
            if (handlerError)
                handlerError();
        });
    },

    //获取当前用户
    getcurrentUser: function () {
        return {
            userId: $.cookie(app.name + "_userId"),
            userName: $.cookie(app.name + "_name"),
            orgId: $.cookie(app.name + "_orgId"),
            orgName: $.cookie(app.name + "_orgName"),


            proxyUserId: $.cookie(app.name + "_userId"),
            proxyUserName: $.cookie(app.name + "_name"),
            proxyOrgId: $.cookie(app.name + "_orgId"),
            proxyOrgName: $.cookie(app.name + "_orgName"),
        };
    },

    //创建流程
    createWorkflow: function () {
        var me = this;
        var workItem;


        $.request("/workflow/create", {
            templateId: me.templateId,
            participants: me.getcurrentUser(),
            instanceName: wfParm.InstanceName(),
            parentInstanceId: 0,
            client: 0
        }, function (data) {
            workItem = data;
            me.instanceId = workItem.instanceId;
        }, false, false);
        return workItem;
    },


    reurnwf: function (activity) {
        this.submit(null, this.workItem, HandleResult.Return, activity.ruleIds);
    },
    //提交
    submit: function (nodes, workItem, handlerResult, ruleIds) {
        debugger;
        var me = this;
        if (wfParm.PreHandler) {
            progress.setProgress(70);
            parm.PreHandler(me, formdata || me.obj, me.currentactivity, next ? next.ACTIVITY : {});
        }
        $.request("/workflow/submit", {
            participants: me.getcurrentUser(),
            participantses: nodes,
            ruleIds: ruleIds ? ruleIds : nextActivity.ruleIds,
            instanceId: workItem.instanceId,
            workItemId: workItem.id,
            result: handlerResult == undefined ? 1 : handlerResult,
            client: 0,
            suggestion: me.getsuggestion()
        }, function () {
            if (parm.AfterHandler) {
                progress.setProgress(90);
                parm.AfterHandler(me, formdata || me.obj, me.currentactivity, next ? next.ACTIVITY : {});
            }
            me.monitor.ReLoad();
            me.monitor.ReDraw();

        });
    },
    //提交演示动画
    animate: function () {
        var me = this;
        var width = window.screen.availWidth;
        var height = window.screen.availHeight;

        function getPx(value) {
            return value + "px";
        }

        this.monitor.ReDraw();
        $('#monitorModal').modal();
        me.setInterval = me.monitor.ShowCurrent();
    },
    //关闭动画
    WaitClose: function () {
        //alert("流程提交成功");
        var me = this;
        var time = 3;
        progress.setProgress(100);
        var divCloseTimer = $("#divCloseTimer");
        $("#divClose").css('display', 'block');
        var interval = window.setInterval(function () {
            --time;
            if (time == 0) {
                if (me.setInterval)
                    window.clearInterval(me.setInterval);
                window.clearInterval(interval);
                window.close();
            }
            else
                divCloseTimer.html($.format("{0}秒后自动关闭...", time))
        }, 1000);

    },

    //关闭窗体
    closeWin: function () {
        try {
            var myparent = window.dialogArguments || opener;
            myparent.refresh();
        } catch (e) {

        }
    },

    //加载附件，预留
    loadAttachment: function () {
        return;
    },

    loadBtn: function (formdata) {
        var that = this;
        if (core.IsDetail)return;
        btnContainer.html('');
        var btn;
        $.request("/workflow/activity/next", {
            activityId: this.currentactivity.id,
            orgId: (that.Instance && that.Instance.orgId) ? that.Instance.orgId : $.cookie(app.name + "_orgId"),
            expression: wfParm.rule(formdata)
        }, function (data) {

            $.each(data.forward, function (i, val) {
                asubmit = GenerateBtn({
                    title: val.activityName,
                    'class': 'glyphicon glyphicon-circle-arrow-right',
                    parm: {'data-handler-result': '1'}

                });
                btnContainer.append(asubmit);
                asubmit.click(function () {
                    nextActivity = val;
                });
            });
            if (data.back && data.back.length > 0) {
                function getWorkitem(activityId) {
                    var item = null;
                    $.each(core.Instance.workitems, function (m, workItem) {
                        if (workItem.activityId == activityId &&
                            workItem.isDel == 0 &&
                            workItem.handleResult == HandleResult.Adopt) {
                            item = workItem;
                            return false;
                        }
                    })
                    return item;
                }

                function getHandler(workItem) {
                    var handler
                    $.each(workItem.workitemHandlers, function (w, workitemHandler) {
                        if (workitemHandler.handleResult == HandleResult.Adopt) {
                            handler = workitemHandler;
                            return false;
                        }
                    })
                    return handler;
                }

                areturn = GenerateBtn({
                    title: "退回",
                    'class': 'glyphicon glyphicon-circle-arrow-left'
                }).addClass('btn');
                var canReturn = $("#backModal");
                var aList = $("#aList", canReturn);
                $.each(data.back, function (i, val) {
                    var li = callbackTemplate.clone();
                    var item = getWorkitem(val.id);
                    var handler = getHandler(item);
                    li.find('.item-booker').html(val.activityName);
                    $(li.find('.item-time span')[0]).html(moment(handler.finishTime).formatUTC("YYYY-MM-DD HH:mm:ss"));
                    $(li.find('.item-time span')[1]).html(handler.handleSuggestion);
                    li.find('.btn-danger').click(function () {
                        if (confirm("确认退回?")) {
                            core.progressInit();
                            core.reurnwf(val);
                        }
                    });
                    aList.append(li);
                });

                areturn.click(function () {
                    if (data.back.length == 1) {
                        aList.find(".btn-danger").click();
                    }
                    else
                        canReturn.modal();
                });
                btnContainer.append(areturn);
                //$(asubmits).before(areturn);

            }


        }, false, false);
        return btnContainer.find("*[data-handler-result=1]");
    },

    loadHistroy: function () {

        function History(data) {
            function gethandlerResult(workitem, handler) {
                if (workitem.activityType != -1) {
                    switch (handler.handleResult) {
                        case HandleResult.Adopt:
                            return "同意";
                        case HandleResult.Return:
                            return "不同意";
                        case HandleResult.Terminated:
                            return "终止";
                        case HandleResult.Transfer:
                            return "转批";
                        case HandleResult.CirculateAdopt:
                            return "阅办";
                    }
                }
                return "";
            }

            var items = data.sort(function (a, b) {
                var aDate = new Date(a.startTime);
                var bDate = new Date(b.startTime);
                return aDate - bDate;
            })
            var rel = 'bordered-' + getstyle();
            var html = "<div><table class='table table-bordered table-hover table-striped dataTable'><thead class='" + rel + "'><tr><th>环节名称</th><th>审批/审核结果</th><th>审批/审核意见</th><th>提交/审批/审核时间</th><th>停留时间</th><th>提交/审批/审核人</th></tr></thead><tbody>";

            $.each(items, function (a, workitem) {
                if (workitem.activityType == 100 || workitem.activityType == 3 || workitem.activityType == 4 || workitem.activityType == 6 || workitem.handleResult == HandleResult.Retrieve)
                    return;

                workitem.workitemHandlers = workitem.workitemHandlers.sort(function (a, b) {
                    var aDate = new Date(a.startTime);
                    var bDate = new Date(b.startTime);
                    return aDate - bDate;
                });
                var count = workitem.workitemHandlers.length;
                html += $.format("<tr><td class='col1' rowspan='{1}'>{0}</td>", workitem.activityName, count);
                var i = 0;

                for (var l = 0; l < count; l++) {
                    var handler = workitem.workitemHandlers[l];
                    i++;
                    var handleTime = moment(handler.finishTime).formatUTC("YYYY-MM-DD HH:mm");
                    var handleSuggestion = handler.handleSuggestion || '';
                    var handleResult = '';

                    handler.handleResult == HandleResult.None ? (handleResult = (workitem.activityType == -1) ? "未提交" : "未审核/审批", handleTime = "") : (handleResult = gethandlerResult(workitem, handler));

                    var exception = l == 0 ? '' : "<tr>";
                    handler.stopTime = handler.handleResult == HandleResult.None ? getStopTime(new Date(), handler.startTime) : getStopTime(handler.finishTime, handler.startTime);
                    html += $.format("{3}<td >{0}</td><td >{1}</td><td>{2}</td><td>{4}</td><td >{5}</td></tr>",
                        handleResult, handleSuggestion, handleTime, exception, handler.stopTime, handler.handleUserName ? handler.handleUserName : handler.userName);
                }
            });
            html += "</tbody></table></div>";


            return html;

        }

        historyConainer.html(History(core.Instance.workitems));
        var items = core.Instance.workitems.sort(function (a, b) {
            var aDate = new Date(a.startTime);
            var bDate = new Date(b.startTime);
            return aDate - bDate;
        });

        var l = core.Instance.workitems.length;
        var divhistoryreview = $("#divhistoryreview");
        $.each(core.Instance.workitems, function (i, workitem) {
            if (workitem.activityType == ActivityType.Condition || workitem.handleResult == HandleResult.Retrieve)
                return;
            var span = $("<span>").html(workitem.activityName);
            span.html(i < l - 1 ? workitem.activityName + "<i class='fa fa-long-arrow-right' style='margin:0 5px;'></i>" : workitem.activityName);
            divhistoryreview.append(span);
        });
    },


}


function Progress() {
    var array, animate, divProgress, isinit = false;


    Progress.prototype.init = function () {
        if (!this.isinit) {
            this.isinit = true;
            divProgress = $("<div>").css({
                'position': 'absolute',
                'bottom': 0,
                'left': 0,
                height: '5px',
                width: '0px',
                'background-color': 'red'
            });
            $('#monitorModal .widget-header').append(divProgress);
        }
        array = [],
            animate = [];
    }

    Progress.prototype.setProgress = function (value) {
        var flag = true;
        $.each(array, function (i, val) {
            if (val > value) {
                flag = false;
                return flag;
            }
        });
        if (flag) {
            animate.push(value);
        }
    }

    Progress.prototype.start = function () {
        Animate(animate[0]);
    }

    function Animate(value) {
        divProgress.animate({width: $.format('{0}%', value)}, 100, null, function () {
            if (value == 100)
                return;
            if (animate.length > 0) {
                try {
                    animate.splice(0, 1);
                } catch (e) {
                }
            }

            var myInterval = window.setInterval($.proxy(function () {
                if (animate.length > 0) {
                    Animate(animate[0]);
                    window.clearInterval(myInterval);
                }

            }), 100);


        });
    }
}

function getStopTime(dt1, dt2) {
    if (!dt1)
        dt1 = new Date();
    else dt1 = moment(dt1)._d;
    dt2 = moment(dt2)._d;
    var diff = dt1.getTime() - dt2.getTime();
    var days = Math.floor(diff / (1000 * 60 * 60 * 24));
    var hours = Math.floor((diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60));
    var s = "";
    var flag = days > 1;
    if (flag)
        s += days + "天";
    flag = flag && hours > 1;
    if (flag)
        s += hours + "小时";
    flag = flag && minutes > 1;
    if (flag)
        s += minutes + "分";
    return s;
}